package com.wangsd.web.controller;

import com.wangsd.core.util.SHA1;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 *  微信相关控制器
 */
@Controller
@RequestMapping("/weixin")
public class WeixinController {

    @RequestMapping("/choseRoom")
    public String choseRoom() {
        return "/weixin/choseRoom";
    }

    /**
     * 微信服务器配置
     * 开启后，用户发送的消息将自动转发到该配置地址，并且在网站中设置的自动回复和自定义菜单将失效
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/configure")
    public void configure(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String signature = request.getParameter("signature");
        System.out.println("-----------signature--------==" + signature);
        String timestamp = request.getParameter("timestamp");
        System.out.println("-----------timestamp--------==" + timestamp);
        String nonce = request.getParameter("nonce");
        System.out.println("-----------nonce--------==" + nonce);
        String echostr = request.getParameter("echostr");
        System.out.println("-----------echostr--------==" + echostr);
        String token = "wangshuodong";
        if (signature != null && timestamp != null && nonce != null && echostr != null) {
            String passStr = "";
            String demos[] = {token, timestamp, nonce};
            Arrays.sort(demos);
            for (int i = 0; i < demos.length; i++) {
                passStr += demos[i];
            }
            System.out.println("-----------passStr--------==" + passStr);
            passStr = SHA1.encode(passStr);
            System.out.println("-----------passStr--------==" + passStr);
            if (signature.equals(passStr)) {
                response.getOutputStream().print(echostr);
            }
        }
    }


}
